package com.venutech.gongan.api;

import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.project.system.domain.SysDept;
import com.ruoyi.project.system.domain.SysUser;
import com.ruoyi.project.system.service.ISysDeptService;
import com.ruoyi.project.system.service.ISysUserService;
import com.shihang.misc.date.DateTimeUtil;
import com.venutech.gongan.common.Constants;
import com.venutech.gongan.service.AuditLogService;
import com.venutech.gongan.service.RzLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import java.util.Date;
import java.util.concurrent.ExecutorService;

@Slf4j
public abstract class AbstractControllerBase {
    @Autowired
    protected ISysDeptService sysDeptService;

    @Autowired
    protected ISysUserService sysUserService;

    @Autowired
    @Qualifier("eventThreadPool")
    protected ExecutorService eventThreadPool;

    @Autowired
    protected RzLogService rzLogService;

    @Autowired
    protected AuditLogService auditLogService;


    protected SysUser currentUser() {
        return sysUserService.selectUserById(SecurityUtils.getUserId());
    }


    protected Long currentUserId() {
        return SecurityUtils.getUserId();
    }

    /**
     * 异步记录日志
     */
    protected void asyncSaveLog(int auditLogType, int logType, String opCondition, String message) {

        eventThreadPool.execute(() -> {
            try {
                SysUser loginUser = currentUser();
                int logId = rzLogService.addRzLog(loginUser.getUserId().intValue(), logType, message, Constants.LOG_OK, Constants.BACK);
                SysDept sysDept = sysDeptService.selectDeptById(loginUser.getDeptId());
                SysUser currentUser = sysUserService.selectUserById(loginUser.getUserId());
                auditLogService.logAudit(loginUser.getUserName(), currentUser.getNickName(), currentUser.getEmployeeNo(),
                        currentUser.getIdNo(), currentUser.getWorkUnitName(), currentUser.getWorkUnitCode(), auditLogType,
                        opCondition, DateTimeUtil.formatDate(new Date(), "yyyyMMddHHmmss"), "1", message, String.valueOf(logId));
            } catch (Exception ex) {
                log.warn("日志记录异常， ex=", ex);
            }
        });
    }
}
